<?php
/**
 * 订单模型
 * @author tangbl
 *
 */
class OrderModel extends Model {
	
	/**
	 * 转到支付(getCode)
	 * 支付处理(notify)
	 * 支付返回(returnUrl)
	 */
	public function callPayFunc($order,$func){
		
		//获取支付参数
		$paycfg = C("PAYMENT_TYPE");
		$type   = trim($order['payment']);
		$payarr = $paycfg[$type];
		$cfg    = $payarr["cfg"];
		$param  = $payarr["param"];
		$ordcfg = $payarr["order"];
		$orderno= $order["orderno"];
		
		//$orders = array();
		if(is_array($ordcfg)){
			foreach($ordcfg as $k=>$v){
				$order[$k] = $order[$v] ;
			}
		}

		$payments = array();
		foreach($cfg as $k=>$v){
			if(in_array($k, $param)){
				$payments[$k] = HTTP_URL.U("$v","orderno=".$orderno) ;
			}else{
				$payments[$k] = $v ;
			}
		}
		//F($func."_".$type."_0",$order);
		//F($func."_".$type."_1",$payments);
		import('ORG.Payment.'.$type);
		$paypal = new $type($payments);
		$flag   = $paypal->$func($order,$payments);

		return $flag;
	}
	
	/**
	 * 判断是否为预定餐
	 * @param unknown_type $outlet
	 */
	public function getYuding($outlet){
		
		$now    = time();
		$yuding = 2;
		
		$start  = strtotime(date('Y-m-d').' '.$outlet['starthours']);
		$end    = strtotime(date('Y-m-d').' '.$outlet['endhours']);
		$start1 = strtotime(date('Y-m-d').' '.$outlet['starthours1']);
		$end1   = strtotime(date('Y-m-d').' '.$outlet['endhours1']);
		
		if($outlet['starthours1']){
			//如果开始时间大于当前时间并且结束时间小于当前时间，那么就是暂停营业时间
			if(($start1>$now||$end1<$now)&&($start>$now||$end<$now)){
				$yuding = 1;
			}
		}else{
			if($start>$now || $end<$now){
				$yuding = 1;
			}
		}
		$outlet['yuding'] = $yuding;
		return $outlet;
	}
	
	/**
	 * 查询菜品是否需要延长时间
	 * @param array $list 购物车列表
	 */
	public function getDishesTime($list){
		
		$time = 0;
		
		foreach($list['list'] as $k=>$v){
			if($v['dishes_time']>$time){
				$time    = $v['dishes_time'];
				$title   = $v['title'];
				$entitle = $v['entitle'];
			}
		}
		
		$list['time']   = $time;
		$list['title']  = $title;
		$list['ntitle'] = $entitle;
		
		return $list;
	}
	
	/**
	 * 检查订单类型
	 * Product
	 * Groupou
	 * Seckill
	 */
	function checkOrder(){
	
		$table = session(C('CART_TABLE'));
		$select= session(C('CART_SELECTED'));
		$flag  = false;
		if($table && $select){
			$module = get_array_key("ORDER_TABLE",$table);
			if(is_array($module)){
				$flag   = true;
			}
		}
	
		return array("flag"=>$flag,"table"=>$module);
	}
	
	public function getCityTel($arr){
		
		$config = F("Sysconfig");
		$tel    = "";
		
		if($arr['cityid']==850){
			$tel = $config['cfg']['telbj'];
		}elseif($arr['cityid']==866){
			$tel = $config['cfg']['telsh'];
		}elseif($arr['cityid']==867){
			$tel = $config['cfg']['telgz'];
		}else{
			$tel = $config['cfg']['telsy'];
		}
		return $tel;
	}
	
	/**
	 * 获取确认订单页面的商品列表
	 * return array
	 */
	public function getConfirmList($rows){
	
		$cart   = session(C('CART_SELECTED'));
		$select = explode(",",$cart);
	
		$table  = $rows['cart'];
		$model  = D("$table");
		$list   = $model->getConfirmList($select);
		return $list;
	}
	
	/**
	 * 添加订单操作
	 * 添加订单详情
	 * @param $order  订单模型
	 * @param $addrid 地址主键编号
	 * @param $rows
	 */
	public function dealOrder($order,$addrid=0,$rows){
	
		$user   = getMember();
		$userid = $user['id'];
		$outlet = $order->outletid;
		$orderno= createOrderNo();
		
		$order->tableid  = $rows['table'];
		$order->orderno  = $orderno;
		$order->addtime  = time();
		$order->userid   = $userid;
		$order->status   = 1;
		$outlet          = $order->outletid;
	
		$list   = $this->getConfirmList($rows);
		if(is_array($list['list'])){
			$order  = $this->addOrderDetail($list['list'],$userid,$order,$rows);
			$weight = $list["weight"];
			$order->weight = $weight;
		}else{
			return false;
		}
		
		//优惠券会员卡处理
		$order = $this->couponVipDeal($order);
		
		//订单地址处理
		if($addrid){
			$data = M("Address")->find($addrid);
			$order->addrid   = $data['id'];
			$order->realname = $data['realname'];
			$order->mobile   = $data['mobile'];
			$order->address  = $data['address'];
			$order->email    = $data['email'];
				
			$area  = $data['area'];
			//处理配送方式
			$order = $this->shipDeal($order,$area);
		}
		
		$oldid = $order->add();
		
		if($oldid){
			
			//删除购物所选的商品
			$this->emptyConfirmCart($userid,$rows['table']);
			
			//订单关联门店
			if($rows['outlet'] && $outlet){
				$this->orderOutlet($outlet,$oldid,$userid);
			}else{
				$map['id'] = $oldid;
				sendRest("Tip/tipord",$map);
			}
			return $orderno;
			
		}else{
			return false;
		}
	}
	
	/**
	 * 处理配送方式
	 */
	public function shipDeal($order,$area){
		
		$m['shipid'] = I("param.ship",0,"intval");
		$m['area']   = $area;
		$m['amount'] = $order->amount;
		$m['weight'] = $order->weight;
		$m['total']  = $order->totalfee;
		
		if($m['area'] && $m['total'] && $m['shipid'] && $m['weight']){
			$json = sendRest("Shipping/calc", $m);
			if($json['status'] == 1){
				$shipfee  = $json["data"];
				$totalfee = $order->totalfee;
				$order->shipfee  = $shipfee;
				$order->totalfee = $totalfee+$shipfee;
			}
		}
		return $order;
	}
	
	/**
	 * 其他支付方式订单确认
	 * 获取用户地址列表和地址数据字典
	 * 获取可使用的支付方式
	 * 获取会员卡和优惠卷
	 */
	public function dealConfirm($rows){
	
		$user   = getMember();
		$userid = $user['id'];
		$model  = D("Address");
	
		$rows['addr'] = $model->getUserAddress($userid);
		$rows['dict'] = $model->getAddressDict();//dump($rows['dict']);exit();
		
		$cfgs = C("PAYMENT_TYPE");
		$pays = array();
	
		foreach($cfgs as $k=>$v){
			if($v['show'] == 1 || $v['show'] == 2){			
				$pays[$k]['key']     = $k;
				$pays[$k]['checked'] = $v['checked'];
				$pays[$k]['lang']    = $v['lang'];
				$pays[$k]['show']    = $v['show'];
			}
		}
		$rows['pays'] = $pays ;

		if($rows['vip']){
			$module = D("Member");
			$rows['yhj'] = $module->getUserCoupon();
			$rows['vip'] = $module->getUserVip();
		}
		
		if($rows['ship']){
			$json = sendRest("Shipping/ship", array("fields"=>"id,code,title,remark"));
			$rows['ship'] = $json['data'];
		}
	
		return $rows;
	}
	
	
	/**
	 * 添加订单详情
	 * 增加商品的购买数量
	 * 用户统计(数据跟踪)
	 * @param array $list  需要添加到订单详情的商品列表
	 * @param int   $usrid 用户编号
	 * @param Model $order 订单模型
	 * @param array $rows  详情模型
	 */
	public function addOrderDetail($list, $userid, $order,$rows){
		
		$model    = M("OrderDetail");
		$table    = $rows['table'];
	    $product  = M("$table");
	  //$product  = M("Product");
		
		$content  = I("post.content");
		$amount   = 0 ;$total    = 0 ;
		$outleid  = empty($order->outletid) ? 0 : $order->outletid;
		
		foreach($list as $v){
				
			//增加商品的购买数量:团购和秒杀亦是增加商品的购买数量
			$where[$rows['id']] = $v['pid'];
			$product->where($where)->setInc("buynum",1);
				
			$map['pid']        = $v['pid'];
			$map['title']      = $v['title'];
			$map['price']      = $v['sprice'];
			$map['amount']     = $v['num'];
			$map['totalprice'] = intval($v['num']) * doubleval($v['sprice']);
			$map['content']    = $content[$v['pid']];
			$map['orderno']    = $order->orderno;
			$map['outletid']   = $outleid;
			$map['addtime']    = time();
			$map['userid']     = $userid;
			$map['tableid']    = $table;
				
			$integral += intval($v['jifen']);  //购买商品赠送总积分
			$amount += intval($v['num']);      //购买商品总数量
			$total  += $map['totalprice'];     //购买商品总价格
		    $model->add($map);
		}
		
		//更新用户可使用积分 应该使用接口
		$this->editUserUseIntegral($integral,$userid);

		$order->totalfee = $total;
		$order->amount   = $amount;
	
		//增加用户统计
		/* $log['ordtotal'] = 1 ;
		$log['prototal'] = $order->amount ;
		$log['allprice'] = $order->totalfee ;
		saveTotalLog($log); */
	
		return $order;
	}
	
	/**
	 * 删除购物车选中的商品w
	 * @param $userid int 用户编号
	 *
	 */
	public function emptyConfirmCart($userid,$table){
		
		if($table == "Product"){
			$map['userid'] = $userid ;
			$selected      = explode(",",session(C('CART_SELECTED')));
			$map['id']     = array("in",$selected);
			M("MemberCart")->where($map)->delete();
		}
		session(C('CART_SELECTED'),NULL);
		session(C('CART_TABLE'),NULL);
	}
	
	/**
	 * 订单支付时的 优惠券 以及 会员卡 优惠操作
	 * @param  对象    $order
	 * @return 对象    $order
	 */
	public function couponVipDeal($order){
		
		$coupon   = I("param.coupon","","trim");
		$userid   = session(C('USER_AUTH_KEY'));
		
		$orderfee = $order->totalfee;  //实际金额
		$cardfee  = 0;                 //优惠券金额
		$totalfee = $order->totalfee;  //订单金额
	
		if($coupon == "ActyhjCoupon"){
			$couponid = I("param.yhjid",0,"intval");
			$map['total']    = $totalfee;
			$map['couponid'] = $couponid;
			$json  = sendRest("Coupon/find",$map);
			
			if($json['status'] == 1){
				$totalfee = $json['data'];
				$cardfee  = $orderfee-$totalfee;
				
				//添加优惠卷使用记录
				$data['total']   = $orderfee;
				$data['coupon']  = $cardfee;
				$data['type']    = 3;
				$data['couponid']= $couponid;
				$data['userid']  = $order->userid;
				$data['remark']  = "订单号:".$order->orderno.",优惠金额:".$cardfee;
				$json = sendRest("Coupon/addlog", $data);
			}
			
		}elseif($coupon == "ActvipcardUser"){
			$couponid = I("param.vipid",0,"intval");
			$model = D('Actvipcard');
			$json  = $model->getUserVipDetail($userid);
			
			if($json['status'] == 1){
				$discount = intval($json['data']['discount']);
				$totalfee = $orderfee*($discount/100);
				$cardfee  = $orderfee-$totalfee;
				
				//添加会员卡使用记录
				$data['total']  = $orderfee;
				$data['val']    = $cardfee;
				$data['act']    = 3;
				$data['cascade']= 2;
				$data['userid'] = $order->userid;
				$data['remark'] = "订单使用会员,金额:".$orderfee.",优惠金额:".$cardfee;
				$json = sendRest("Vip/addmoney", $data);
			}
		}else{
			$couponid = 0 ;
		}//exit();
		$order->totalfee = $totalfee;
		$order->orderfee = $orderfee;
		$order->cardfee  = $orderfee-$totalfee;
		$order->cardtype = $coupon;
		$order->cardid   = $couponid;
	
		return $order;
	}
	
	
	/**
	 * 订单门店
	 * 系统操作记录
	 * 订单关联门店
	 */
	public function orderOutlet($outletid,$oldid,$userid){
	
		$map['outid']  = $outletid;
		$map['status'] = 2;
		$map['userid'] = $userid;
		$map['id']     = $oldid;
		sendRest("Order/userStatus",$map);
	}
	
	/**
	 * paypal快捷支付确认订单
	 * 获取用户地址列表和地址数据字典
	 * 获取会员卡和优惠卷
	 */
	public function confirmPaypal($orderno){
		
		$user   = getMember();
		$userid = $user['id'];
		$model  = D("Address");
		
		$rows['addr'] = $model->getUserAddress($userid);
		$rows['dict'] = $model->getAddressDict();
	
		return $rows;
	}
	
	/**
	 * paypal快捷支付处理订单
	 * 处理地址
	 */
	public function dealPaypal($order,$addrid){
		
		$orderno = $order->orderno;
		//订单地址处理
		if($addrid){
			
			$data = M("Address")->find($addrid);
			$order->addrid   = $data['id'];              //地址id
			$order->realname = $data['realname'];        //收件人姓名
			$order->mobile   = $data['mobile'];          //电话
			$order->email    = $data['email'];           //电邮
			$order->address  = $data['address'];         //地址
			
			$order->save();
		}
	
		return $orderno;
	}
	
	/**
	 * 评论订单详情中的商品
	 * @param $title 评论内容
	 * @param $score 评分
	 * @param $id    订单主键
	 * 
	 */
	public function orderComment($title,$score,$id){
		
		$map['id']     = $id;
		$map['userid'] = session(C('USER_AUTH_KEY'));
		$data   = $this->where($map)->find();
		
		if($data['id'] && $data['ispay']==1){
			
			$m['orderno'] = $data["orderno"];
			$ids = M("OrderDetail")->where($m)->getField("pid",true);
			
			$comment = M("Comment");
			$model   = M("Product");
			$array   = $title;
			
			foreach($array as $n=>$m){
				
				if(!in_array($n, $ids)){
					continue;
				}
				if(empty($m)){
					$m = L("mb_form_recomment_default");
				}
				$star = $score[$n];
				$arr['pid']      = $n;
				$arr['title']    = $m;
				$arr['star']     = $star;
				$arr['outletid'] = $data['outletid'];
				$arr['orderno']  = $data['orderno'];
				$arr['tableid']  = $data['tableid'];
				$arr['addtime']  = time();
				$arr['nickname'] = getSession("USER_AUTH_MODEL","nickname");
				$arr['mobile']   = session(C('USER_AUTH_ACCOUNT'));
				$arr['userid']   = session(C('USER_AUTH_KEY'));
				$comment->add($arr);
				
				//增加商品的评论数量:团购和秒杀亦是增加商品的评论数量
				$model->where(array("id"=>$n))->setInc('recnum',1);
			}
			$map['iscomment'] = 1 ;
			$this->save($map);
			return true; 
		}else{
			return false;
		}
	}
	
	/**
	 * 根据支付方式获得对应的支付参数
	 * @param $pay String 支付方式
	 * @param $cfg String
	 */
	public function getPayConfg($pay,$cfg){
		
		$cfgs  = C("PAYMENT_TYPE");
		$arrs  = $cfgs[$pay];
		
		return $arrs[$cfg];
	}
	
	/**
	 * 更新会员可使用积分
	 * @param int $integral 购买商品赠送积分总和
	 * @param int $userid   用户id
	 */
	public function editUserUseIntegral($integral,$userid){
		
		$model = M("ActvipcardUser");
		
		$map['userid'] = $userid;
		$data = $model->where($map)->setInc("use_jifen",$integral);
	}
	
	/**
	 * 根据类型将数组分割成两个不同的数组
	 */
	private function get_price_type($data){
		
		$arr = $data['list'];
		
		foreach ($arr as $k => $v){
			if($v['flag']=="dishes"){
				$array['dishes'][] = $v;
			}else{
				$array['drink'][]  = $v;
			}
		}
		return $array;
	}
	/**
	 * 计算价格
	 * @param unknown_type $data
	 */
	private function count_price($data,$coupon){
		
		$total_dprice   = 0;   //没有打折或者没有特价时的商品总价
		$total_tprice   = 0;   //商品特价或者折扣后的总价
		$total_yhprice  = 0;   //打折或者特价商品的优惠总价
		$totalfee       = 0;   //菜品或者酒水饮料总金额
		$settlefee      = 0;   //成本总价格
		
		$coupons = $coupon/100; //获取折扣如 0.98 = 98/100
		foreach ($data as $k => $v){
			if($v['isspec']==1){
			    
				$yhprice  = $v['dprice']-$v['tprice'];  //单件商品优惠价格  = 商品原价 - 商品特价
				$yhprices = $yhprice*$v['num'];         //商品优惠总价  = 商品优惠价格 * 商品数量
				
				$total_yhprice += $yhprices;  
				$total_tprice  += $v['xjprice'];
				$total_dprice  += $total_yhprice+$v['xjprice'];
				
			}else{
				if($coupons){
					$zkprice = $v['xjprice']*$coupons;   //折扣价格 = 小计*折扣比例
					$totals  = $v['tprice']*$coupons;
					
					$total_tprice  += $zkprice;
					$total_dprice  += $v['xjprice'];
					$total_yhprice += $v['xjprice']-$zkprice;
				}else{
					$total_tprice  += $v['xjprice'];
					$total_dprice  += $v['xjprice'];
					$total_yhprice += $total_dprice-$total_tprice;
				}
			}
			//$settlefee += $v['mprice']*$v['num']+$v['psPrice'];
			$settlefee += ($v['mprice']+$v['psPrice'])*$v['num'];
		}
		
		$datas['total_dprice']  = $total_dprice;
		$datas['total_tprice']  = $total_tprice;
		$datas['total_yhprice'] = $total_yhprice;
		
		$datas['totalfee']      = $total_tprice;
		$datas['settlefee']     = $settlefee;
		return $datas;
		
	}
	/**
	 * 计算订单金额,不加服务费
	 * @param unknown_type $data
	 */
	private function count_order_price($dishes,$drink){
		
		$dishes_total_dprice  = $dishes['total_dprice'];
		$dishes_total_tprice  = $dishes['total_tprice'];
		$dishes_total_yhprice = $dishes['total_yhprice'];
		$dishes_totalfee      = $dishes['totalfee'];
		$dishes_settlefee     = $dishes['settlefee'];
		
		$drink_total_dprice   = $drink['total_dprice'];
		$drink_total_tprice   = $drink['total_tprice'];
		$drink_total_yhprice  = $drink['total_yhprice'];
		$drink_totalfee       = $drink['totalfee'];
		$drink_settlefee      = $drink['settlefee'];
		
		//$data['total_dprice']    = $dishes_total_dprice  + $drink_total_dprice;  //商品总金额
		$data['total_tprice']    = $dishes_total_tprice  + $drink_total_tprice;	   //商品特价总金额
		$data['total_yhprice']   = $dishes_total_yhprice + $drink_total_yhprice;   //优惠总金额
		$data['dishes_totalfee'] = $dishes_totalfee;                               //菜品总金额
		$data['drink_totalfee']  = $drink_totalfee;								   //酒水饮料总金额									
		$data['settlefee']       = $dishes_settlefee;                              //成本总金额
		$data['receivefee']      = $data['total_tprice']- $data['settlefee'];	   //实收金额

		return $data;
	}
	
	/**
	 * 计算总价，特价商品不参与餐厅折扣
	 */
	public function get_tprice_total($data,$coupon){
		
		$array  = $this->get_price_type($data);                            //获取菜品饮品数组
		$dishes = $this->count_price($array['dishes'], $coupon['coupon']); //计算菜品价格
		$drink  = $this->count_price($array['drink'],  $coupon['coupon']); //计算饮品价格
		$total  = $this->count_order_price($dishes,$drink);                //计算菜品和饮品总价
		
		return $total;
	}
	
	/**
	 * 根据优惠时间段计算订单金额
	 * @param unknown_type $sdltime 
	 * @param unknown_type $obegin
	 * @param unknown_type $oend
	 * @param unknown_type $total
	 * @param unknown_type $dlivery
	 * @param unknown_type $model
	 * @return Ambigous <number, unknown>
	 */
	public function get_order_total($status,$total,$model){

		$dlivery = $model['shipfee'];//获取服务费
		$dlivery = $dlivery>=0?$dlivery:0;
		
		$sdltime   = $model['sdltime'];
		$is_exempt = I("is_exempt");
		
		$model['cardfee']    = $total['total_yhprice'];           //优惠总金额
		$model['dishesfee']  = $total['dishes_totalfee'];         //菜品总金额
		$model['drinkfee']   = $total['drink_totalfee'];          //酒水饮料总金额
		$model['settlefee']  = $total['settlefee'];               //成本总金额
		$model['receivefee'] = $total['receivefee']+ $dlivery;    //实收金额
		$model['orderfee']   = $total['total_tprice'] + $dlivery; //实际支付金额
		
		if($status['status']==1){
			$model['exemptfee']  = $status['price'];       //减免的费用
		}
		
		/*else{
			$model['receivefee'] = $model['receivefee']+$status['price'];
			$model['orderfee']   = $model['orderfee']+$status['price'];
			$model['shipfee']    = $dlivery+$status['price']; //如果不是减免时间段，则加上服务费
		}*/
		
		return $model;
	}
	
	/**
	 * 将餐厅免配送费的时间段转换成时间戳
	 */
	public function get_outlet_timestamp($map,$model,$total){
			      
		$week    = explode(',',$map['week']); //餐厅选择的星期数组
		$nowweek = date('w');                 //获取当前星期几
		$sdltime = $model['sdltime'];         //配送时间
		$status  = -1;                        //返回状态
		
		$begin   = strtotime(date("Y-m-d")." ".$map['exemptbegin']); //餐厅免配送费开始时间 
		$end     = strtotime(date("Y-m-d")." ".$map['exemptend']);   //餐厅免配送费结束时间
		$nowweek = $nowweek!=0?$nowweek:7;  //英文版date获取到的星期天为0，这里要转化一下
		
		if($total['total_tprice']>=50){
			if($map['is_exempt']==1){
				if(in_array($nowweek, $week)){
					if($sdltime>=$begin&&$sdltime<=$end){
						$status = 1;
					}
				}
			}
		}
		
		return array('status'=>$status,'price'=>$map['exemptprice']);
	}
	
	/**
	 * 获取餐厅详情
	 */
	public function getOutletDetail($model){
		
		$data = session("outlet_coupon");
		
		if(empty($data)){
			$map['id'] = $model['outletid'];
			$data = sendRest('BDC/Outlet/detail',$map);
			$data = $data['data'];
		}
		return $data;
	}
	
	//计算服务费
	public function getDliveryfee($distance){
		$config = F('Sysconfig');
		$query  = addressJsonDecode();
		$juli   = $config['sys'][$query['encity']];
		
		foreach($juli as $k=>$n){
			if($n[0]<$distance && $distance<$n[1]){
				$dliveryfee = $n[3];
			}
		}
		return $dliveryfee;
	}

	/**
	 * 下订单时，如果配送费为0，则重新计算一次
	 */
	public function cullShipfee($data){
	
		//餐厅详情
		$outlet   = M('Outlet')->find($data['outletid']);
		$c_lng    = $outlet['longitude'];
		$c_lat    = $outlet['latitude'];
		$y_lng    = $data['user']['pointlng'];
		$y_lat    = $data['user']['pointlat'];

		//城市配置
		$city    = addressJsonDecode();
		$cityarr = C('CITYID');
		$title   = $cityarr[$city['cityid']][1];
		$url     = "http://api.map.baidu.com/direction/v1";
		
		//计算距离
		$map['origin']             = $c_lat.",".$c_lng; //餐厅经纬度
		$map['destination']        = $y_lat.",".$y_lng; //用户经纬度
		$map['output']             = "json";
		$map['ak']                 = "6RQGXCYLSCZzLuPgZnnSMMrd";
		$map['region']             = $title;
		$map['origin_region']      = $title;
		$map['destination_region'] = $title;
		
		Log::write('cullShipfee1:'.var_export($map,true),Log::ERR);
		$json = curlGet($url,$map);
		Log::write('cullShipfee2:'.var_export($json,true),Log::ERR);
		
		$distance   = $json['result']['routes'][0]['distance'];
		$dliveryfee = $this->getDliveryfee($distance);
		Log::write('cullShipfee3:'.$dliveryfee.',distance:'.$distance,Log::ERR);
		
		//判断是否处于减免配送费用时间
		$exempt = D('Restaurant')->getDelivery($outlet,$dliveryfee);
		Log::write('cullShipfee4:'.var_export($exempt,true),Log::ERR);
		return $exempt['sever'];
	}
	
	public function getHtml($id){
	
		//订单信息
		$json = sendRest("OMS/Order/detail",array("id"=>$id));
	
		//餐厅信息
		$outletid = $json['data']['outletid'];
		$outlet   = sendRest("BDC/Outlet/detail",array("id"=>$outletid));
	
		//订单详情信息
		$map['orderno'] = $json['data']['orderno'];
		$data = sendRest("OMS/Order/dlist",$map);
	
		$totalPrice = 0;
		foreach($data['data'] as $k=>$v){
			$totalPrice += $v['price']*$v['amount'];
			$data['data'][$k]['attr'] = json_decode($v['attr'],true);
			if($v['flag']=="dishes"){
				$cat['id'] = $v['pid'];
				$view = sendRest("RMS/Product/dishesDetail",$cat);
				$data['data'][$k]['detail']         = $view['data'];
				$data['data'][$k]['detail']['gnfr'] = json_decode($view['data']['gnfr'],true);
			}
		}
	
		$dlist  = $data['data'];
		$detail = $json['data'];
		$outlet = $outlet['data'];
	
		$html .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
		$html .= '<html xmlns="http://www.w3.org/1999/xhtml">';
		$html .= '<head>';
		$html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		$html .= '<title>回执</title>';
		$html .= '</head>';
		$html .= '<body style="overflow-y:scroll;">';
		$html .= '<table style="font-size:10px;";  class="print"  width="100%" border="0" cellpadding="0" cellspacing="0">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<td class="title" align="center" style="font-size:22px;">K.K.RABBIT FOOD DELIVERY SERVICE</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td class="website" align="center" style="font-size:16px;">www.kkrabbit.com.cn</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td class="telephone" align="center" style="font-size:16px;">Tel:400-020-1717&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax:(021)5239-9205</td>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		$html .= '<tr>';
		$html .= '<td>';
		$html .= '<table style="padding-top:20px;vertical-align:center;" class="print_table1" width="100%" border="0" cellpadding="0" cellspacing="0">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th></th>';
		$html .= '<td></td>';
		$html .= '<th class="odd"></th>';
		$html .= '<td></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td width="110" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td width="220" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td class="space" style=" height:1px;border-left: 1px solid #333333;border-top: 1px solid #333333;"></td>';
		$html .= '<td width="110" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th style="" width="110">Delivery To:<br/>客户名称：</th>';
		$html .= '<td style="" width="220">'.$detail['username'].'</td>';
		$html .= '<td style="border-left: 1px solid #333333; width:10px;"></td>';
		$html .= '<th style=" " width="110" class="odd">Order No:<br/>订单号：</th>';
		$html .= '<td style="">'.$detail['orderno'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2"></td>';
		$html .= '<td colspan="3" class="space" style="border-left: 1px solid #333333; height:5px;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th>Mobile:<br/>电话：</th>';
		$html .= '<td>'.$detail['mobile'].'</td>';
		$html .= '<td style="border-left: 1px solid #333333; width:10px;"></td>';
		$html .= '<th class="odd" style="">Order Date:<br/>订单日期：</th>';
		$html .= '<td>'.date('m/d',$detail['addtime']).'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2"></td>';
		$html .= '<td colspan="3" class="space" style="border-left: 1px solid #333333; height:5px;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th>Address:<br/>地址：</th>';
		$html .= '<td>'.$detail['address'].'</td>';
		$html .= '<td style="border-left: 1px solid #333333; width:10px;"></td>';
		$html .= '<th class="odd" style="">Order Time:<br/>订餐时间：</th>';
		$html .= '<td>'.date('m/d H:i:s',$detail['addtime']).'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2"></td>';
		$html .= '<td colspan="3" class="space" style="border-left: 1px solid #333333; height:5px;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th>&nbsp;</th>';
		$html .= '<td>&nbsp;</td>';
		$html .= '<td style="border-left: 1px solid #333333; width:10px;"></td>';
		$html .= '<th class="odd" style="">Target Delivery:<br/>配送时间：</th>';
		$html .= '<td>'.date('m/d H:i',$detail['sdltime']).'&nbsp;&nbsp;~&nbsp;&nbsp;'.date('m/d H:i',$detail['edltime']);
	
		if($detail['isyuding']==1){
			$html .= '（预定餐）';
		}
	
		$html .= '</td></tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2" style=" height:1px;border-bottom: 1px solid #333333;"></td>';
		$html .= '<td colspan="3" class="space" style=" height:1px;border-left: 1px solid #333333;border-bottom: 1px solid #333333;"></td>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tfoot>';
		$html .= '<tr>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th style="">Restaurant:</th>';
		$html .= '<td style="">'.$outlet['entitle'].'</td>';
		$html .= '<td style="width:10px;"></td>';
		$html .= '<th style="" class="odd">餐厅：</th>';
		$html .= '<td style="">'.$outlet['title'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2" style=" height:1px;"></td>';
		$html .= '<td colspan="3" class="space" style=" height:1px;"></td>';
		$html .= '</tr>';
		$html .= '</tfoot>';
		$html .= '</table>';
		$html .= '<table class="print_table2" width="100%" border="0" cellpadding="5" cellspacing="0">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Item ID<br/>编号</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Item<br/>菜名</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Quantity<br/>数量</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Property<br/>属性</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Unit Price<br/>单价</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Comment<br/>要求</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333; text-algin:right;" class="right">Price<br/>总价</th>';
		$html .= '</tr>';
		$html .= '</thead><style>body{line-height:1;}</style>';
		$html .= '<tbody>';
	
	
		//菜品饮品开始
		foreach($dlist as $k=>$v){
			if($v['flag']=='dishes'){
				$html .= '<tr>';
				$html .= '<td style="">'.$v['pno'].'</td>';
				$html .= '<td style="">'.$v['title'].'<br/>'.$v['entitle'].'</td>';
				$html .= '<td  align="center" style="">'.$v['amount'].'</td>';
				$html .= '<td style="">';
					
				if($v['attr']){
					foreach($v['attr'] as $l=>$m){
						$html .= '<span class="entitle">'.$m['title'].'（'.$m['entitle'].'）：</span>';
							
						foreach($m['config'] as $d=>$n){
							$html .= '<span>'.$n['title'].'（'.$n.entitle.'）';
							if($n['num']){
								$html .= '（'.$n['num'].'份/portion）';
							}
							$html .= '</span>';
						}
						$html .= '<br/>';
					}
				}
					
				$html .= '</td>';
				$html .= '<td style="">￥'.$v['price'].'</td>';
				$html .= '<td style="">'.$v['content'].'</td>';
				$html .= '<td style="text-algin:right;" class="right">￥'.$v['total'].'</td>';
				$html .= '</tr>';
			}
		}
	
		$html .= '<tr>';
		$html .= '<td colspan="5"></td>';
		$html .= '<td colspan="2" class="total right" style="border-top:2px solid #000"><span>SubTotal/小计：</span>￥'.number_format($detail["dishesfee"]+$detail['cardfee'],2).'</td>';
		$html .= '</tr>';
	
		$html .= '<tr><td colspan="7" style="border-top:1px solid #000"></td></tr>';
		$num   = 0;
		
		foreach($dlist as $k=>$v){
			if($v['flag']=='drink'){
				$html .= '<tr>';
				$html .= '<td style="">'.$v['pno'].'</td>';
				$html .= '<td style="">'.$v['title'].'<br/>'.$v['entitle'].'</td>';
				$html .= '<td style="">';
					
				if($v['attr']){
					foreach($v['attr'] as $l=>$m){
						$html .= '<span class="entitle">'.$m['title'].'（'.$m['entitle'].'）：</span>';
							
						foreach($m['config'] as $d=>$n){
							$html .= '<span>'.$n['title'].'（'.$n.entitle.'）';
							if($n['num']){
								$html .= '（'.$n['num'].'份/portion）';
							}
							$html .= '</span>';
						}
						$html .= '<br/>';
					}
				}
					
				$html .= '</td>';
				$html .= '<td  align="center" style="">'.$v['amount'].'</td>';
				$html .= '<td style="">￥'.$v['price'].'</td>';
				$html .= '<td style="">'.$v['content'].'</td>';
				$html .= '<td style="text-algin:right;" class="right">￥'.$v['total'].'</td>';
				$html .= '</tr>';
				$num  ++;
			}
		}
		
		if($num>0){
			$html .= '<tr>';
			$html .= '<td colspan="5"></td>';
			$html .= '<td colspan="2" class="total right" style="border-buttom:1px solid #FFF;border-top:2px solid #000">';
			$html .= '<span>SubTotal/小计：</span>￥'.$detail['drinkfee'];
			$html .= '</td>';
			$html .= '</tr>';
			$html .= '<tr><td colspan="7" style="border-top:1px solid #000"></td></tr>';
		}
		//菜品饮品结束
	
		$html .= '</tbody>';
		$html .= '</table>';
		$html .= '<table class="print_table3" width="100%" border="0" cellpadding="3" cellspacing="0">';
		$html .= '<tr>';
		$html .= '<td>Memo:<br/>备注：</td>';
		$html .= '<td width="225">'.$detail['content'].'</td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Restaurant Total:<br/>餐厅金额</td>';
		$html .= '<td class="right">￥'.number_format($detail['dishesfee']+$detail['cardfee'],2).'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td></td>';
		$html .= '<td rowspan="4" style="width:225px;">';
		$html .= '<div>';
		
		$drink = C('IS_SEND_DRINK');
		if($detail['isdrink']){
			$html .= '免费饮品：'.$drink[$detail['isdrink']]['zh-cn'].'（'.$drink[$detail['isdrink']]['en-us'].'）';
		}
		if($detail['isinvoice']==1){
			$html .= '发票：抬头（'.$detail['invoice_title'].'）';
		}
		
		$html .= '</div>';
		$html .= '</td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Adjustment:<br/>调整费：</td>';
		$html .= '<td class="right">￥'.$detail['b_price'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td></td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Service Charge:<br/>服务费：</td>';
		$html .= '<td class="right">￥'.$detail['shipfee'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td></td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Wine & Drink:<br/>酒饮料： </td>';
		$html .= '<td class="right">￥'.$detail['drinkfee'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td></td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Discount:<br/>优惠：</td>';
		$html .= '<td class="right">￥'.$detail['cardfee'].'</td>';
		$html .= '</tr>';
		$html .= '<tfoot>';
		$html .= '<tr>';
		$html .= '<td colspan="2"  style="width:385px;"></td>';
		$html .= '<td class="o_total dercoration" style="text-decoration: underline;">Order Total:<br/>总价：</td>';
		$html .= '<td class="right o_total">￥'.number_format($detail["orderfee"]+$detail['b_price'],2).'</td>';
		$html .= '</tr>';
		$html .= '</tfoot>';
		$html .= '</table>';
		$html .= '</td>';
		$html .= '</tr>';
		$html .= '</tbody>';
		$html .= '<tfoot>';
		$html .= '<tr>';
		$html .= '<td class="print_foot" style="text-align:right;">'.date("Y-m-d H:i:s").'</td>';
		$html .= '</tr>';
		$html .= '</tfoot>';
		$html .= '</table>';
		$html .= '</body>';
		$html .= '</html>';
	
		return $html;
	}
}
		

?>